
public class RowPriority2 {

	int[] alfabeto = new int[26];
	NodeH2 nodeMinor;
	int size;
	
	/**
	 * Construtor
	 * 
	 * @param string
	 */
	public RowPriority2(String string) {
		int freq;
		
		nodeMinor = null;
		size = 0;

		for (int i=0; i<26; i++) {
			
			alfabeto[i] = count((char)(65+i),string);
			
			freq = count((char)(65+i),string);
			if (freq > 0) {
				NodeH2 newNode = new NodeH2((char)(65+i)+"",freq);
				insert(newNode);
			}
		}

	}

	/**
	 * Metodo
	 * 
	 * @param c
	 * @param s
	 * @return
	 */
	public static int count(char c, String s) {
		int retorno = 0;
		
		for (int i = 0 ; i < s.length() ; i++){
			if (s.charAt(i) == c) {
				retorno++;
			}
		}
		
		return retorno;
	}

	/**
	 * Metodo
	 * 
	 * @return
	 */
	public int size() {
		return size;
	}

	/**
	 * Metodo
	 * 
	 * @return
	 */
	public NodeH2 extractMin() {
		NodeH2 nodeNext = nodeMinor.getNext();
		NodeH2 nodeMinor = this.nodeMinor;
		if (nodeNext != null) {
			nodeNext.setPrevious(null);
			this.nodeMinor.setNext(null);
		}
		this.nodeMinor = nodeNext;
		size--;
		return nodeMinor;
	}

	/**
	 * Metodo
	 * 
	 * @param z
	 */
	public void insert(NodeH2 z) {
		if (size == 0) {
			nodeMinor = z;
			size++;
		} else {
			
			NodeH2 key = nodeMinor;
			NodeH2 nodePrevious = null;
			NodeH2 nodeNext = null;
			
			int aux1, aux2;
			NodeH2 naux1, naux2;
			
			while (true) {
				
				aux2 = size;
				
				aux1 = key.frequency;
				aux2 = z.frequency;
				naux1 = key.getPrevious();
				naux2 = key.getNext();
				
				
				if(key.frequency<z.frequency && key.getNext()!=null) {
					key = key.getNext();
				} else {
					if (key.getPrevious()!=null && key.getNext()!=null) {
						nodePrevious = key.getPrevious();
						
						key.setPrevious(z);
						z.setNext(key);
						nodePrevious.setNext(z);
						z.setPrevious(nodePrevious);
						
						size++;
						break;
					} else {
						if (key.getPrevious()==null) {
							//este no vai ter quer ser o nodeMinor
							key.setPrevious(z);
							z.setNext(key);
							nodeMinor = z;

							size++;
							break;
						} else {
							nodePrevious = key.getPrevious();
							
							key.setPrevious(z);
							z.setNext(key);
							
							nodePrevious.setNext(z);
							z.setPrevious(nodePrevious);

							size++;
							break;
						}
					}
				}
			}
		}
	}

	public NodeH2 getMinor() {
		return nodeMinor;
	}

}
